package com.zzw.quartztest.service.impl;

import com.zzw.quartztest.job.TestConcurrencyJob;
import com.zzw.quartztest.service.IQuartzTestService;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

@Service
public class QuartzTestServiceImpl implements IQuartzTestService {

    private static final String JOB_KEY_PREFIX = "jobName";
    private static final String TRIGGER_KEY_PREFIX = "triggerName";
    public static final String JOB_DATA_KEY = "jobDataKey";

    @Autowired
    private Scheduler scheduler;

    /**
     * 应用启动时创建定时任务
     */
    @PostConstruct
    public void init() throws SchedulerException {

        // 创建一个Cron规则的定时任务
        Class<? extends Job> jobClass = TestConcurrencyJob.class;
        //构建job信息
        Long jobId = 1L;
        String jobGroup = "default";

        JobKey jobKey = JobKey.jobKey(JOB_KEY_PREFIX + jobId, jobGroup);
        JobDetail jobDetail = JobBuilder.newJob(jobClass).withIdentity(jobKey).build();

        //表达式调度构建器
        CronScheduleBuilder cronScheduleBuilder = CronScheduleBuilder.cronSchedule("*/2 * * * * ? *");
//        cronScheduleBuilder.withMisfireHandlingInstructionFireAndProceed();
        // 构建trigger
        TriggerKey triggerKey = TriggerKey.triggerKey(TRIGGER_KEY_PREFIX + jobId, jobGroup);
        CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(triggerKey)
                .withSchedule(cronScheduleBuilder).build();

        //放入参数，Job的execute方法可以获取
        jobDetail.getJobDataMap().put(JOB_DATA_KEY, jobId);

        // 判断job是否存在
        if (scheduler.checkExists(jobKey)) {
            scheduler.deleteJob(jobKey);
        }
        scheduler.scheduleJob(jobDetail, trigger);

        // 是否暂停任务
        boolean pause = false;
        if (pause) {
            scheduler.pauseJob(jobKey);
        }
    }
}
